#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void DoanotherThing()
{
  printf("I am doing anotherthing\n");
}

void ChildRun()
{
    int cnt = 5;
    while(cnt)
    {
        printf("I am child process, pid: %d, ppid:%d, cnt: %d\n", getpid(), getppid(), cnt);
        sleep(1);
        cnt--;
    }
}

int main()
{
    printf("I am father, pid: %d, ppid:%d\n", getpid(), getppid());

    pid_t id = fork();
    if(id == 0)
    {
        // child
        ChildRun();
        printf("child quit ...\n");
        exit(123);
    }
    // fahter
    while(1)
    {
      int status = 0;
      pid_t rid = waitpid(id, &status, WNOHANG);
     if(rid==0)
    {
      usleep(10000);
      printf("child is running ,check next time!\n");
      DoanotherThing();
    }
      else if(rid > 0)
    {
      //判断子进程是否是因为异常退出
      if(WIFEXITED(status))
      {
        printf("wait success, child exit code:%d\n", WEXITSTATUS(status));//获取子进程退出码：123      
      }
      else
      {
        printf("child process quit unnormal!\n");
      }
      break;
    }
    else
    {
        printf("wait failed !\n");
        break;
    }

   }
}
